<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<h2>测试一下WebSocket站点吧</h2>
<br>
<input id="message" type="text">
<button onclick="sendMessage()">发送消息</button>
<button onclick="closeWebSocket()">关闭连接</button>
<div id="context"></div>
<script>
    var websocket = null;
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://127.0.0.1:8001/ws")
        console.log(websocket)
    } else {
        alert('Not support websocket')
    }

    websocket.onerror = function () {
        appendMessage("error");
    }
    websocket.onopen = function () {
        appendMessage("open");
    }
    websocket.onmessage = function (event) {
        appendMessage(event.data);
    }
    websocket.onmessage = function () {
        appendMessage("close");
    }

    function appendMessage(message) {
        var context = $("context").html() + "<br/>" + message;
        $("#context").html(context);
    }

    function closeWebSocket() {
        websocket.close();
    }

    function sendMessage() {
        var message = $("#message").val();
        websocket.send(message)
    }
</script>
</body>
</html>